package org.qq120011676.fileserver.fileserver.helper.impl;

import lombok.SneakyThrows;
import org.apache.commons.io.FileUtils;
import org.qq120011676.fileserver.fileserver.config.FileserverConfig;
import org.qq120011676.fileserver.fileserver.helper.BaseStorageHelper;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.stereotype.Component;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.MessageFormat;

@ConditionalOnExpression("!'${fileserver.local.path:}'.isEmpty()")
@Component
public class LocalStorageHelper extends BaseStorageHelper {
    private final FileserverConfig.Local localConfig;

    @SneakyThrows
    public LocalStorageHelper(FileserverConfig fileserverConfig) {
        super(fileserverConfig);
        localConfig = fileserverConfig.getLocal();
        Path path = Paths.get(localConfig.getPath());
        // 自动创建所有不存在的父目录
        Files.createDirectories(path);
    }

    @SneakyThrows
    @Override
    public void save(String objectName, byte[] bytes) {
        File file = new File(MessageFormat.format("{0}{1}",
                handlePath(localConfig.getPath()),
                objectName));
        FileUtils.writeByteArrayToFile(file, bytes);
    }

    @SneakyThrows
    @Override
    public byte[] get(String objectName) {
        File file = new File(MessageFormat.format("{0}{1}",
                handlePath(localConfig.getPath()),
                objectName));
        return FileUtils.readFileToByteArray(file);
    }

    @Override
    public boolean exist(String objectName) {
        File file = new File(MessageFormat.format("{0}{1}",
                handlePath(localConfig.getPath()),
                objectName));
        return file.exists();
    }

    @SneakyThrows
    @Override
    public void delete(String objectName) {
        File file = new File(MessageFormat.format("{0}{1}",
                handlePath(localConfig.getPath()),
                objectName));
        FileUtils.deleteQuietly(file);
    }

    private String handlePath(String path) {
        String endStr = "/";
        if (path.endsWith(endStr)) {
            return path;
        }
        return MessageFormat.format("{0}{1}", path, endStr);
    }
}
